<?php
declare (strict_types=1);

namespace app\index\controller;

use addons\OssBackup\facade\OssBackup;
use app\common\model\Logs;
use app\common\model\Statistics;
use app\common\model\User;
use \addons\V4\admin\model\OrderTemporary;

class Callback
{

    /**
     * @return void
     * 自动备份
     */
    public function autoOssBackup()
    {
        try {
            $route = 'callback/autoOssBackup.log';
            $result = OssBackup::auto();
            Logs::write($route, json_encode($result));
        } catch (\Exception $e) {
            Logs::write($route, $e->getMessage());
        }
    }

    /**
     * @return void
     * 更新统计
     */
    public function statistics()
    {
        Statistics::_timing();
    }


    public function alipayCallback()
    {
        try {
            $route = 'callback/alipayCallback.log';
            $pay = \AliPay\App::instance(config('pay')['alipay']);
            $data = $pay->notify();
            if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                // @todo 更新订单状态，支付完成

                Logs::write($route, '订单支付成功');
                return 'SUCCESS';
            } else {
                // @todo 回调验证失败处理
                Logs::write($route, '回调验证失败:' .json_encode($data));

            }
        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::write($route, $e->getMessage());
        }
    }


    public function wechatCallback()
    {
        try {
            $route = 'callback/wechatCallback.log';
            $wechat = \WeChat\Pay::instance(config('pay')['wechat']);
            $data = $wechat->getNotify();
            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                // @todo 更新订单状态，支付完成


                // 返回接收成功的回复
                Logs::write($route, '订单支付成功');
                return $wechat->getNotifySuccessReply();
            } else {
                // @todo 回调验证失败处理
                Logs::write($route, '回调验证失败：' . json_encode($data));
            }

        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::write($route, $e->getMessage());

        }
    }


    public function typesOf()
    {

        try {
            $route = 'callback/typesOf.log';
            /**
             * 有赞推送服务消息接收示例
             */
            $myClientId = "d56a4f0b1d4879c192"; //应用的 client_id
            $myClientSecret = "bbb8e8fd20171abdd15f5fe999dbbabb"; //应用的 client_secret
            $httpRequestBody = file_get_contents('php://input');
            $httpSign = $_SERVER['HTTP_EVENT_SIGN'];
            $httpType = $_SERVER['HTTP_EVENT_TYPE'];
            $httpClientId = $_SERVER['HTTP_CLIENT_ID'];
            $sign = md5(sprintf('%s%s%s', $myClientId, $httpRequestBody, $myClientSecret));
            if($sign != $httpSign) {
                return json_encode(array("code" => 0, "msg" => "faild"));
            }

            Logs::write($route, $httpType);
            if($httpType == "SCRM_CUSTOMER_EVENT") {
                $httpData = json_decode($httpRequestBody, true);
                User::WriteMember($httpData);
            }elseif($httpType == "salesman_customer_relation_change_biz")
            {
                $httpData = json_decode($httpRequestBody, true);
                User::recommend($httpData);
            }elseif($httpType == "OPEN_PUSH_SCRM_MEMBER_MERGE")
            {
                $httpData = json_decode($httpRequestBody, true);
                User::merge($httpData);
            }elseif($httpType == "trade_TradePaid")
            {
                $httpData = json_decode($httpRequestBody, true);
                OrderTemporary::WriteOrder($httpData);
            }elseif($httpType == "trade_TradeSuccess")
            {
                $httpData = json_decode($httpRequestBody, true);
                OrderTemporary::TradeSuccess($httpData);
            }
            return json_encode(array("code" => 0, "msg" => "success"));
        } catch (\Exception $e) {
//            dump($e->getMessage());
            Logs::write($route, $e->getMessage());
        }
    }



}